import { useEffect, useState } from 'react';

import { ReactComponent as Chevron } from '@/assets/images/shared/icon-chevron.svg';
import { TabProps } from '@/shared/interfaces';
import { ModalPage } from '@/widgets/ModalPage';
import cn from 'classnames';
import { useWindowSize } from 'usehooks-ts';

import cs from './Tabs.module.scss';

export const Tabs = ({ tabs }: { tabs: TabProps[] }) => {
  const tabsWithValidData = tabs?.filter((tab) => tab.data !== null);
  const { width } = useWindowSize();
  const [currentTab, setCurrentTab] = useState<TabProps | undefined>(
    tabsWithValidData?.length > 0 ? tabsWithValidData[0] : tabs?.[0],
  );
  const [isOpen, setIsOpen] = useState(false);
  const handleClick = (tab: TabProps) => {
    setCurrentTab(() => tab);
    if (width <= 1024) {
      setIsOpen(() => true);
    }
  };
  const handleClose = () => {
    setIsOpen(() => false);
  };
  useEffect(() => {
    if (!currentTab?.data || width > 1023) {
      handleClose();
    }
  }, [width]);
  if (!tabs.length) {
    return <></>;
  }
  return (
    <>
      <div className={cs.tabs}>
        <div
          className={cn(
            tabs.filter((item) => item.data !== null).length === 1 && width < 1024
              ? cs.tabsOne_header
              : cn(cs.tabs_header, tabs.filter((item) => !item.data) && cs.disabledHeader),
          )}
        >
          {width > 1024
            ? tabs.map((tab) => (
                <button
                  className={cn(cs.tab, currentTab?.id === tab.id && cs.active, !tab.data && cs.disabledTab)}
                  disabled={!tab.data}
                  key={tab.id}
                  onClick={() => handleClick(tab)}
                  type="button"
                >
                  <div>{tab.title}</div>
                  <div className={cs.mobile_arrow}>
                    <Chevron />
                  </div>
                </button>
              ))
            : tabs
                .filter((item) => item.data !== null)
                .map((tab) => (
                  <button
                    className={cn(cs.tab, currentTab?.id === tab.id && cs.active)}
                    disabled={!tab.data}
                    key={tab.id}
                    onClick={() => handleClick(tab)}
                    type="button"
                  >
                    <div className={cs.title}>{tab.title}</div>
                    <div className={cs.mobile_arrow}>
                      <Chevron />
                    </div>
                  </button>
                ))}
        </div>
        <div className={cs.content}>{currentTab?.data}</div>
      </div>
      <ModalPage handleClose={handleClose} isMobile={false} isOpen={!!currentTab?.data && isOpen && width < 1024}>
        <div className={cs.modal_title}>{currentTab?.title}</div>
        <div>{currentTab?.data}</div>
      </ModalPage>
    </>
  );
};
